package graph;

import java.util.LinkedList;
import java.util.Queue;

public class Solution {

    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, -1, 1};

    public int orangesRotting(int[][] grid) {
        int res = 0;
        int fresh = 0;
        Queue<int[]> queue = new LinkedList<>();
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 2) {
                    queue.offer(new int[]{i, j});
                } else if (grid[i][j] == 1) {
                    fresh++;
                }
            }
        }
        while (!queue.isEmpty() && fresh > 0) {
            int len = queue.size();
            res++;
            for (int i = 0; i < len; i++) {
                int[] tmp = queue.poll();
                int x = tmp[0];
                int y = tmp[1];
                for (int d = 0; d < 4; d++) {
                    int x1 = x + dx[d];
                    int y1 = y + dy[d];
                    if (x1 >= 0 && x1 < grid.length && y1 >= 0 && y1 < grid[0].length && grid[x1][y1] == 1) {
                        grid[x1][y1] = 2;
                        fresh--;
                        queue.offer(new int[]{x1, y1});
                    }
                }
            }
        }
        return fresh > 0 ? -1 : res;
    }


    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println(solution.orangesRotting(new int[][]{{0, 1}}));
    }
}
